# frozen_string_literal: true

class RuleEntity
  class GeneralRule
    class Condition
      class Dsl < RuleEntity::GeneralRule::Condition
        has_one :formula, as: :formulable, dependent: :destroy

        def build_archive_params
          raise 'Unsupported.'
        end

        def deep_clone_to_draft
          entity = super
          entity.create_formula! formula.slice(:type, :content)
          entity
        end

        def update_draft(params)
          super
          update_formula(params[:formula]) if params[:formula].present?
        end

        def force_validate
          super

          validate_formula
        end

        def only_fire?(params)
          condition_params = rule_conditions.each_with_index.map do |condition, index|
            ["cond#{index.next}".to_sym, condition.fire(params, schema.input_types_map)]
          end.to_h
          formula.fire(condition_params)
        end

        private

        def update_formula(params)
          formula ? formula.update!(params.slice(:content)) : create_formula!(params.slice(:type, :content))
        end

        def validate_formula
          raise 'missing formula.' if formula.nil?

          logger.debug { 'TODO' }
        end
      end
    end
  end
end
